<template>
  <div class="page-container">
    <div class="tool-bar">
      <div class="form-tool">
        <el-form
          ref="queryForm"
          class="query-form"
          label-width="0px"
          :model="filtersData"
          :inline="true"
          @submit.prevent
        >
          <el-form-item>
            <ac-tree
              v-model="filtersData.modelId"
              data-url="/system/dataModel/queryTree"
              typeSelect="model"
              @change="changeDataModel"
            />
          </el-form-item>
          <el-form-item>
            <ac-select
              v-model="filtersData.fieldName"
              :options="fieldOptionList"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="filtersData.fieldValue"
              placeholder="查询关键字"
              clearable
              @change="queryPage"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="queryPage($event)"
            ><ac-icon iconId="018dc9c3efe489a7d117" style="margin-right: 5px" />查询</el-button>
            <el-button
              v-if="dataModel.type === '1'"
              type="danger"
              @click="deleteDataList($event)"
            ><ac-icon iconId="018dc9c3efd3a0502886" style="margin-right: 5px" />删除</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!--表格栏-->
    <el-table
      v-loading="loading"
      v-if="fieldList.length > 0"
      element-loading-text="数据加载中..."
      ref="dataTable"
      :show-overflow-tooltip="{
        'effect': 'light',
        'raw-content': false,
        'placement': 'bottom',
        'popper-class': 'padding-10-15'
      }"
      class="data-table"
      :data="tableDataList"
      :border="true"
      :stripe="true"
      @sort-change="sortChange"
      @row-click="clickRow"
    >
      <template #empty>
        <div class="el-table__empty-block">
          <img src="@/assets/images/no-data.png" style="width: 100px" alt />
          <span style="min-width: 100px">暂无数据</span>
        </div>
      </template>
      <el-table-column
        header-align="center"
        align="center"
        type="selection"
        width="40"
        :show-overflow-tooltip="false"
      ></el-table-column>
      <el-table-column
        v-for="field in fieldList"
        header-align="center"
        align="center"
        :prop="field.fieldName"
        :label="field.showName + '<br/>(' + field.fieldName + ')'"
        :key="field.fieldName"
        :sortable="true"
        :min-width="field.fieldName.endsWith('id') ? 170 : field.fieldName.endsWith('time') ? 160 : 120"
      >
        <template #header>
          {{field.showName}}
          <br v-if="field.showName !== field.fieldName" />
          {{field.showName !== field.fieldName ? field.fieldName : ''}}
        </template>
        <template v-slot="scope">
          <span v-if="field.fieldType === '时间'" class="overflow-ellipsis">
            {{date.formatLongDate(scope.row[field.fieldName])}}
          </span>
          <span
            v-else
            class="overflow-ellipsis"
          >{{scope.row[field.fieldName]}}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="dataModel.type === '1'"
        header-align="center"
        align="center"
        label="操作"
        fixed="right"
        :show-overflow-tooltip="false"
        width="200"
      >
        <template v-slot="scope">
          <el-button
            type="info"
            @click.stop="showData($event, scope.row)"
            link
          >查看</el-button>
          <el-button
            type="primary"
            @click.stop="editData($event, scope.row)"
            link
          >修改</el-button>
          <el-button
            type="success"
            @click.stop="copyData($event, scope.row)"
            link
          >复制</el-button>
          <el-button
            type="danger"
            @click.stop="deleteData($event, scope.row)"
            link
          >删除</el-button>
        </template>
      </el-table-column>
      <template v-if="$slots.append" #append>
        <slot name="append"></slot>
      </template>
    </el-table>
    <!--分页栏-->
    <div class="pagination-box" v-if="fieldList.length > 0">
      <div class="pagination-box-right">
        <el-pagination
          layout="total, prev, pager, next, jumper, sizes"
          :current-page="pageRequest.pageNumber"
          :page-sizes="[10, 20, 50, 100, 500]"
          :page-size="pageRequest.pageSize"
          :total="data.totalRecord"
          @current-change="refreshPage"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!--新增编辑界面-->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      append-to-body
      destroy-on-close
      draggable
      fullscreen
    >
      <div class="page-container">
        <el-form
          :model="formData"
          class="no-padding fit-form"
          label-width="0"
          ref="dataForm"
          label-position="right"
          :rules="rules"
          :disabled="!dialogEdit"
          :hide-required-asterisk="!dialogEdit"
        >
          <el-row class="fit-form-row">
            <el-col :span="24" class="fit-form-col">
              <el-form-item prop="json" class="fit-form-item">
                <el-input
                  type="textarea"
                  v-model="formData.json"
                  style="height: 100%; display: flex; flex-direction: row;"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible = false"
        >取消</el-button>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="primary"
          @click="submitForm"
          :loading="editLoading"
        >提交</el-button>
        <el-button
          v-if="!dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible = false"
        >关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '@/http/api';
import tool from "@/utils/tool";
import date from "@/utils/date";

const filtersData = ref({});
const fieldList = ref([]);
const fieldOptionList = ref([]);

const pageRequest = ref({
  pageNumber: 1,
  pageSize: 20
});
const data = ref({
  pageNumber: 1,
  pageSize: 20,
  totalPage: 0,
  totalRecord: 0
});
const tableDataList = ref([]);
const loading = ref(false);

const dataTable = ref();
const dataModel = ref({type: '2'});
const dialogTitle = ref('');
const dialogVisible = ref(false);
const dialogEdit = ref(false);
const editLoading = ref(false);
const dataForm = ref();
const formData = ref({});
const rules = ref({
  json: [{required: true, message: '请数据', trigger: ['blur', 'change']}],
});

const changeDataModel = () => {
  fieldList.value = [];
  fieldOptionList.value = [];
  tableDataList.value = [];
  if (filtersData.value.modelId) {
    api.post("/system/dataModel/queryBy", {id: filtersData.value.modelId}).then(res => {
      dataModel.value = res.data || [];
    });

    api.post("/system/dataField/queryList", {modelId: filtersData.value.modelId}).then(res => {
      fieldList.value = (res.data || []).filter(item => item.fieldType !== '派生');

      (res.data || []).forEach(field => {
        fieldOptionList.value.push({value: field.showName, key: field.fieldName});
      });

      refreshPage(1);
    });
  }
};

const queryPage = (event) => {
  event && event.currentTarget && event.currentTarget.blur();
  refreshPage(1);
};

const refreshPage = (pageNumber) => {
  pageRequest.value.pageNumber = pageNumber;
  findPage();
};

const handleSizeChange = (pageSize) => {
  pageRequest.value.pageSize = pageSize
  refreshPage(1)
};

const sortChange = (column) => {
  if (column.order === 'ascending') {
    pageRequest.value.sortField = column.prop
    pageRequest.value.sortType = 'asc'
  } else if (column.order === 'descending') {
    pageRequest.value.sortField = column.prop
    pageRequest.value.sortType = 'desc'
  } else {
    pageRequest.value.sortField = null
    pageRequest.value.sortType = null
  }
  refreshPage(1);
};

const clickRow = (row) => {
  dataTable.value.clearSelection()
  dataTable.value.toggleRowSelection(row)
}

const findPage = () => {
  if (!filtersData.value.modelId) return;

  const params = {};
  if (filtersData.value.fieldName) {
    params[filtersData.value.fieldName] = filtersData.value.fieldValue;
  }

  loading.value = true;
  api.post(
    "/system/codeless/" + filtersData.value.modelId + "/page",
    Object.assign({}, params, pageRequest.value)
  ).then((res) => {
    data.value = res;
    tableDataList.value = res.data;
    pageRequest.value.pageSize = res.pageSize || pageRequest.value.pageSize;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

const showData = (event, row) => {
  event.currentTarget.blur();
  const json = tool.deepClone(row);
  const result = {};
  for (let field of fieldList.value) {
    result[field.fieldName] = json[field.fieldName] === 0 ? 0 : json[field.fieldName] || null;
  }
  formData.value.json = JSON.stringify(result, null, 2);
  dialogEdit.value = false;
  dialogVisible.value = true;
  dialogTitle.value = "数据展示";
};

const editData = (event, row) => {
  event.currentTarget.blur();
  const json = tool.deepClone(row);
  const result = {};
  for (let field of fieldList.value) {
    result[field.fieldName] = json[field.fieldName] === 0 ? 0 : json[field.fieldName] || null;
  }
  formData.value.json = JSON.stringify(result, null, 2);
  dialogEdit.value = true;
  dialogVisible.value = true;
  dialogTitle.value = "数据修改";
};

const copyData = (event, row) => {
  event.currentTarget.blur();
  const json = tool.deepClone(row);
  const result = {};
  for (let field of fieldList.value) {
    if (field.primaryKey !== '1') {
      result[field.fieldName] = json[field.fieldName] === 0 ? 0 : json[field.fieldName] || null;
    }
  }
  formData.value.json = JSON.stringify(result, null, 2);
  dialogEdit.value = true;
  dialogVisible.value = true;
  dialogTitle.value = "数据复制";
};

const deleteData = (event, row) => {
  event.currentTarget.blur();
  let id = null;
  let value = null;
  for (let field of fieldList.value) {
    if (field.primaryKey === '1') {
      id = field.fieldName;
      value = row[field.fieldName];
    }
  }

  if (id && value) {
    const data = {};
    data[id] = value;

    ElMessageBox.confirm('请确认是否删除？', '提示', {type: 'info'}).then(() => {
      editLoading.value = true
      api.post("/system/codeless/" + filtersData.value.modelId + "/delete", data).then((res) => {
        ElMessage.success(res.message);
        findPage()
        editLoading.value = false;
      }).catch(() => {
        editLoading.value = false;
      });
    }).catch(()=>{});
  }
};

const deleteDataList = (event) => {
  event.currentTarget.blur();

  let idField = null;
  for (let field of fieldList.value) {
    if (field.primaryKey === '1') {
      idField = field.fieldName;
      break;
    }
  }
  const selectRows = dataTable.value.getSelectionRows();
  const dataList = [];
  selectRows.forEach(row => {
    const data = {};
    data[idField] = row[idField];
    dataList.push(data);
  });

  if (dataList && dataList.length > 0) {
    ElMessageBox.confirm('请确认是否删除？', '提示', {type: 'info'}).then(() => {
      editLoading.value = true
      api.post("/system/codeless/" + filtersData.value.modelId + "/delete", {dataList: dataList}).then((res) => {
        ElMessage.success(res.message);
        findPage()
        editLoading.value = false;
      }).catch(() => {
        editLoading.value = false;
      });
    }).catch(()=>{});
  }
};

const submitForm = () => {
  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true;
        api.post(
          "/system/codeless/" + filtersData.value.modelId + "/save",
          JSON.parse(formData.value.json)
        ).then((res) => {
          ElMessage.success(res.message);
          dialogVisible.value = false;
          findPage()
          editLoading.value = false;
        }).catch(() => {
          editLoading.value = false;
        });
      }).catch(()=>{});
    }
  });
};

</script>

<style scoped>
.tool-bar {
  display: inline-block;
  width: 100%;
}
.tool-bar>div{
  display: inline-block;
}
.form-tool {
  float: left;
}
.form-tool .el-form .el-form-item,
.form-tool  .el-form .el-form-item {
  margin-bottom: 5px;
}
.form-tool :deep(.el-input),
.form-tool :deep(.el-select) {
  width: 150px!important;
  text-align: left;
}
.form-tool .el-form--inline .el-form-item {
  margin-right: 10px;
}
.data-table {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}
.data-table :deep(td .cell) {
  padding: 0 5px!important;
}
.data-table :deep(td.el-table-column--selection .cell) {
  padding: 0!important;
}
.data-table :deep(td.edit-cell) {
  padding: 0!important;
}
.data-table :deep(td.edit-cell .cell) {
  padding: 0!important;
}
.data-table .button-box :deep(.el-button) {
  margin: 0 5px;
}
.el-table :deep(.first-row) {
  color: #FF9764;
  font-weight: bold;
}
.el-table :deep(.el-table__fixed-right) {
  background: #FFFFFF;
}
.el-table :deep(.el-table__inner-wrapper) {
  height: 100px;
  flex-grow: 1;
}
.el-table__empty-block {
  min-height: 200px;
  display: flex;
  flex-direction: column;
}
.pagination-box {
  margin-top: 10px;
  display: flex;
}
.pagination-box-right {
  max-width: 100%;
  text-align: right;
  flex: 1 1 auto;
  flex-wrap: nowrap;
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
}
.pagination-box-right :deep(.el-pagination) {
  padding-right: 0;
}
.pagination-box-right :deep(.el-pagination__editor) {
  margin-right: 8px;
}
.pagination-box-right :deep(.is-last) {
  margin-left: 10px;
  margin-right: 0;
}
</style>